package com.basin.auth.core.strategy.impl;

import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.basin.auth.common.form.UPForm;
import com.basin.auth.core.strategy.LoginStrategy;
import com.basin.common.core.exception.BasinAssert;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author: Sam ZHONG | sammy1997@aliyun.com
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class UPLoginStrategy implements LoginStrategy {

    @Override
    public String login(Object credentials) {
        // 转化
        UPForm upForm = JSON.to(UPForm.class, credentials);
        BasinAssert.isTrue(ObjUtil.isNotNull(upForm), "表单数据不能为空");
        BasinAssert.isTrue(StrUtil.isNotBlank(upForm.getUsername()), "用户名不能为空");
        BasinAssert.isTrue(StrUtil.isNotBlank(upForm.getPassword()), "密码不能为空");
        // 查找用户

        // 先尝试清空上次缓存
        StpUtil.logout("sammy", "web");
        StpUtil.login("sammy", new SaLoginModel() {{
            setDevice("web");
            setExtra("tenant_id", "cloudAI");
        }});
        String tokenValue = StpUtil.getTokenValue();
        log.info("LOGIN RETURN TOKEN: {}", tokenValue);
        return tokenValue;
    }
}
